<template>
  <el-container style="min-height: 100%">
    <el-header style="height: 120px; min-width: 800px; overflow-y: auto">
      <div
        style="
          display: flex;
          justify-content: space-between;
          align-items: center;
        "
      >
        <!-- 放按钮的 -->
        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-direction: column;
            margin-right: 40px;
          "
        >
          <el-button
            style="margin: 10px 0"
            type="success"
            @click="drawer = true"
            >新增条目</el-button
          >
          <el-button
            style="margin: 10px 0"
            v-if="multiSelection.length === 0"
            type="info"
            disabled
            >删除选择</el-button
          >
          <el-button
            v-else
            style="margin: 10px 0"
            type="danger"
            @click="delMulti"
            >删除选择</el-button
          >
        </div>
        <div>
          <el-form>
          </el-form>
        </div>
        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-direction: column;
            margin-left: 40px;
          "
        >
          <el-button style="margin: 10px 0" type="primary" @click="querybtn"
            >查 询</el-button
          >
          <el-button style="margin: 10px 0" type="info" @click="queryReset"
            >重 置</el-button
          >
        </div>
      </div>
    </el-header>
    <el-main
      style="
        max-height: calc(100% - 270px);
        min-height: 0;
        margin: 20px 0;
        padding: 0;
        min-width: 600px;
        overflow-y: auto;
      "
    >
      <el-table
        max-height="calc(100vh - 340px)"
        :data="tableData.list"
        style="align-self: center; width: 100%; height: 100%"
        @selection-change="handleSelectionChange"
      >
        <!-- 首列多选框 用于批量删除 -->
        <el-table-column type="selection" width="55" />
        <!-- 遍历属性字段 listTittle为定义的字段名称列表 -->
        <template v-for="(item, index) in listTittle" :key="index">
          <!-- 固定首列id值 -->
          <el-table-column
            v-if="index == 0"
            fixed
            :prop="item.prop"
            :label="item.label"
          />
          <!-- id条目不可编辑 -->
          <el-table-column
            v-else-if="item.prop.endsWith('Id') || item.prop.endsWith('id')"
            :prop="item.prop"
            :label="item.label"
          >
            <template #default="scope">
              <span class="itemContent">{{ scope.row[item.prop] }}</span>
            </template>
          </el-table-column>
          <!-- 使用日期选择进行编辑的字段 -->
          <el-table-column
            v-else-if="
              item.prop.includes('date') ||
              item.prop.includes('Date') ||
              item.prop.includes('Time') ||
              item.prop.includes('time')
            "
            :prop="item.prop"
            :label="item.label"
          >
            <template #default="scope">
              <!-- 编辑状态 -->
              <el-date-picker
                v-if="editIndex === scope.row[0]"
                v-model="scope.row[item.prop]"
                type="datetime"
                placeholder="请选择时间"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
              <!-- 浏览状态 -->
              <span v-else class="itemContent">{{ scope.row[item.prop] }}</span>
            </template>
          </el-table-column>

          <!-- 使用输入框进行编辑的字段 -->
          <el-table-column
            v-else
            :prop="item.prop"
            :label="item.label"
          >
            <template #default="scope">
              <!-- 编辑状态 -->
              <div v-if="editIndex === scope.row[0]">
                                <!-- 筛选数字输入框字段 -->
                <el-input
                  v-if="item.prop.includes('contact') || item.prop.includes('Score') || item.prop.includes('score') || item.prop.includes('Num') || item.prop.includes('num')"
                  v-model="scope.row[item.prop]"
                  :placeholder="scope.row[item.prop] + ''"
                  :formatter="(value:any) => `${value}`.replace(/(?!\d)/g, '')"
                  :parser="(value:any) => value.replace(/[^\d.]/g, '')"
                />
                <!-- 筛选文本输入框字段 -->
                <el-input
                  v-else
                  v-model="scope.row[item.prop]"
                  :placeholder="scope.row[item.prop] + ''"
                />
              </div>
              <!-- 浏览状态 -->
              <span v-else class="itemContent">{{ scope.row[item.prop] }}</span>
            </template>
          </el-table-column>
        </template>
        <!-- 操作按钮列 -->
        <el-table-column fixed="right" label="操作" min-width="85px">
          <template #default="scope">
            <!-- 编辑状态 -->
            <el-button-group v-if="editIndex === scope.row[0]">
              <el-button
                type="success"
                icon="edit"
                @click="commitEditItem(scope.row)"
                >提交</el-button
              >
              <el-button
                type="info"
                icon="delete"
                @click="cancelEditItem(scope.row)"
                >取消</el-button
              >
            </el-button-group>
            <!-- 浏览状态 -->
            <el-button-group v-else>
              <el-button type="primary" icon="edit" @click="editItem(scope.row)"
                >编辑</el-button
              >
              <el-button type="danger" icon="delete" @click="delItem(scope.row)"
                >删除</el-button
              >
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </el-main>
    <el-footer>
      <el-pagination
        style="justify-content: center; margin: auto"
        :page-count="tableData.pages"
        v-model:current-page="tableData.pageCurrent"
        v-model:page-size="tableData.pageSize"
        :page-sizes="[10, 20, 30, 40]"
        background
        layout="total, sizes, prev, pager, next"
        :total="tableData.total"
        @change="queryReq"
      />
    </el-footer>
  </el-container>
  <el-drawer
    v-model="drawer"
    title="添加比赛"
    direction="rtl"
    size="50%"
  > <CtfContest/>
  </el-drawer>
</template>
<script lang="ts" setup>
//import块
import { userInfo } from "@/stores/userinfo";
import CtfContestApi from "@/api/Backend/CtfContestApi";
import type { FormInstance } from "element-plus";
import CtfContest from "@/components/CtfContest.vue";

const userStore = userInfo();
// 自动化替换表名
const tableName = "Contest";
const drawer = ref(false);
//生命周期函数块
//加载前请求数据
onBeforeMount(() => {
  queryReq();
  getList();
});

//对象定义块

//v-for循环用表头
const listTittle = [
  { prop: "contestId", label: "编号" },
  { prop: "contestName", label: "名称" },
  { prop: "contestType", label: "类型" },
  { prop: "contestStatus", label: "状态" },
  { prop: "contestDifficulty", label: "难度" },
  { prop: "startTime", label: "开始时间" },
  { prop: "endTime", label: "结束时间" },
  { prop: "creator", label: "发起人" },
];

//对话框开关控制对象
const dialogFormVisible = ref(false);
//设置新增表单的校验（数字）待研究
const formRef = ref<FormInstance>();
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      addItem();
      formEl.resetFields();
    } else {
      alert("缺少必填项，请重试");
      formEl.resetFields();
    }
  });
};
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
//新增表单对象
const addForm = reactive({
  contestName: "",
  contestType: "",
  contestStatus: "",
  contestDifficulty: "",
  startTime: "",
  creator: userStore.userInfo.userName,
});
interface TableData {
  list: any[];
  pageCurrent: number;
  pageSize: number;
  total: number;
  pages: number;
}

//查询结果表单对象
const tableData = ref<TableData>({
  list: [],
  pageCurrent: 1,
  pageSize: 10,
  total: 0,
  pages: 0,
});
//查询选项对象
const formInline: { [key: string]: string[] } = reactive({
  contestType: [],
  contestStatus: [],
  contestDifficulty: [],
  creator: [],
  checker: [],
});
//查询参数
const queryArgs = ref<{ [key: string]: any }>({});

//选中行对象
const multiSelection = ref([]);

//函数块
//获取选中行
const handleSelectionChange = (rows: any) => {
  multiSelection.value = rows;
};
//添加表项
const addItem = () => {
  //不需要将属性转换为字符串
  // let props = Object.keys(addForm)
  // props.forEach((item) => {
  //     addForm[item] = addForm[item].toString()
  // })
  //传参为对象不要加{}
  //   axios
  //     .post(urlheader + "/add", addForm)
  //     .then((res) => {
  //       if (res.data.code == 200) {
  //         alert("添加成功");
  //         queryReq();
  //       } else {
  //         alert("添加失败");
  //       }
  //     })
  //     .catch((err) => {
  //       alert("添加失败");
  //       console.log(err);
  //     });
  addFormCLR();
};
//清空添加表单
const addFormCLR = () => {
  Object.keys(addForm).forEach((prop) => {
    addForm[prop as keyof typeof addForm] = "";
  });
};

//获取下拉列表数据
const getList = () => {
  let props = Object.keys(formInline);
  //   props.forEach((item) => {
  //     {
  //       axios
  //         .get(urlheader + "/get" + item)
  //         .then((res) => {
  //           formInline[item] = res.data.data;
  //         })
  //         .catch((err) => {
  //           console.log(err);
  //         });
  //     }
  //   });
};

//重置查询表单
const queryReset = () => {
  queryArgs.value = {};
  tableData.value.pageCurrent = 1;
  tableData.value.pageSize = 10;
  queryReq();
};

//查询按钮重置为第一页
const querybtn = () => {
  tableData.value.pageCurrent = 1;
  queryReq();
};

//发送查询请求
const queryReq = () => {
  let datas = { ...queryArgs.value };
  datas["pageCurrent"] = tableData.value.pageCurrent;
  datas["pageSize"] = tableData.value.pageSize;
  CtfContestApi.queryContest(datas).then((res: any) => {
    tableData.value.list = listFormat(res.data.records);
    tableData.value.pageCurrent = res.data.current;
    tableData.value.pageSize = res.data.size;
    tableData.value.total = res.data.total;
    tableData.value.pages = res.data.pages;
  });
};
let editIndex = ref({
  checkId: -1,
});
let editTemp = null;
//表单项编辑
const editItem = (row) => {
  if (editIndex.value.checkId !== -1) {
    if (confirm("未提交的数据将会丢失，确认继续吗？")) {
      cancelEditItem();
    } else {
      return;
    }
  }
  editIndex.value.checkId = row.checkId;
  editTemp = {};
  listTittle.forEach((item) => {
    editTemp[item.prop] = row[item.prop];
  });
};
//提交表单项编辑
const commitEditItem = (row: any) => {
  CtfContestApi.updateContest(row).then((res) => {
    if (res.code == 200) {
      alert("修改成功");
      queryReq();
      editIndex.value.checkId = -1;
    } else {
      alert("修改失败");
      queryReq();
      editIndex.value.checkId = -1;
    }
  });
};
//取消表单项编辑
const cancelEditItem = (row) => {
  if (row === undefined) {
    for (let i = 0; i < tableData.value.list.length; i++) {
      if (tableData.value.list[i].checkId === editTemp.checkId) {
        tableData.value.list.Object.keys(editTemp.numbers).forEach((prop) => {
          tableData.value.list[prop] = editTemp[prop];
        });
        console.log(tableData.value.list[i]);
        break;
      }
    }
  } else {
    let props = Object.keys(editTemp);
    props.forEach((item) => {
      row[item] = editTemp[item];
    });
  }
  editIndex.value.checkId = -1;
};
//删除表单项
const delItem = (row) => {
  CtfContestApi.deleteContest({ contestId: row.contestId }).then((res) => {
    if (res.code == 200) {
      alert("删除成功");
      queryReq();
    } else {
      alert("删除失败");
    }
  });
};
//批量删除表单项
const delMulti = () => {
  let arr = [];
  multiSelection.value.forEach((item) => {
    arr.push(item.checkId);
  });
  CtfContestApi.deleteContestBatch({ ids: arr }).then((res) => {
    if (res.code == 200) {
      alert("删除成功");
      queryReq();
    } else {
      alert("删除失败");
    }
  });
};
//连表查询结果格式化
const listFormat = (list) => {
  let queryDatas = [];
  let queryItem = {};
  Object.keys(list).forEach((index) => {
    let type = typeof list[index];
    if (type == "object" && list[index] != null) {
      listFormater(list[index], queryItem);
    }
    queryDatas.push(queryItem);
    queryItem = {};
  });
  return queryDatas;
};
//格式化递归器
const listFormater = (from, to) => {
  Object.keys(from).forEach((index) => {
    let type = typeof from[index];
    if (type == "object" && from[index] != null) {
      listFormater(from[index], to);
    } else if (to[index] == null) {
      to[index] = from[index];
    }
  });
};
</script>

<style scoped>
.el-header::-webkit-scrollbar {
  display: none;
}
.el-form-item {
  margin: 10px 20px !important;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  text-align: center;
}
</style>
